#include <iostream>
#include <string>
#include <cstring>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>

// 格式./udpclient server_ip server_port
int main(int argc,char *argv[])
{
    if(argc!=3){
        std::cerr<<"格式错误  正确格式:"<<"./udpclient server_ip server_port"<<std::endl;
        return 1;
    }
    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    //socket
    int socketfd = socket(AF_INET,SOCK_DGRAM,0);
    if(socketfd<0){
        std::cerr<<"socket error"<<std::endl;
        return 2;
    }
    //
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    while(true){
        //发信息
        std::string msg;
        std::cout<<"请输入文字:";
        std::getline(std::cin,msg);
        int n = sendto(socketfd,msg.c_str(),sizeof(msg)-1,0,(struct sockaddr*)&server,sizeof(server));
        (void)n;
        
        //接受信息
        char buf[1024];
        struct sockaddr_in peer;
        socklen_t  peer_len = sizeof(peer);
        bzero((void*)&peer,sizeof(peer));
        int m = recvfrom(socketfd,buf,sizeof(buf)-1,0,(struct sockaddr*)&peer,&peer_len);
        if(m>0){
            buf[m]=0;
            std::cout<<"server回显:"<<buf<<std::endl;
        }
    }
    return 0;
}